package com.tanhua.server;

import cn.hutool.core.collection.CollUtil;
import com.itheima.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentsService {

    @DubboReference
    private CommentsApi commentsApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 添加评论
     * @param movementId 动态Id
     * @param comment 评论内容
     */
    public void saveComments(String movementId, String comment) {
        Long userId = UserHolder.getUserId();

        //构建互动对象
        Comment comment1 = new Comment();
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setCreated(System.currentTimeMillis());
        comment1.setPublishId(new ObjectId(movementId));
        //
//        comment1.setPublishUserId(movementsVo.getUserId());
        comment1.setUserId(userId);
        Integer count = commentsApi.saveComments(comment1);
        log.info("commentCount："+count);
    }

    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //查询关于某动态的评论数据
        List<Comment> movementList = commentsApi.findComments(movementId,CommentType.COMMENT, page, pagesize);

        if (CollUtil.isEmpty(movementList)) {
            return new PageResult();
        }
        //根据Ids查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(movementList, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.getByIds(userIds, null);


        String key = Constants.COMMENTS_LIKE_HASHKEY + UserHolder.getUserId();
        List<CommentVo> commentVos = movementList.stream().map((movement -> {
            UserInfo userInfo = userInfoMap.get(movement.getUserId());
            if (userInfo == null) {
                return null;
            }
            CommentVo commentVo = CommentVo.init(userInfo, movement);
            if (redisTemplate.opsForHash().hasKey(key, movement.getId().toHexString())) {
                commentVo.setHasLiked(1);
            }
            return commentVo;
        })).filter(Objects::nonNull).collect(Collectors.toList());

        return new PageResult(page, pagesize, 0L, commentVos);
    }


    /**
     * 动态点赞喜欢
     * @param movementId
     * @return 喜欢点赞数
     */
    public Integer countLike(String movementId) {
        Long userId = UserHolder.getUserId();

        //查询用户是否已经点赞
        Boolean aBoolean = commentsApi.hasComment(movementId, userId, CommentType.LIKE);
        if (aBoolean) {
            disLikeComment(movementId);
            throw new BusinessException(ErrorResult.likeError());
        }
        //构造互动对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));//动态Id
        comment.setCommentType(CommentType.LIKE.getType());//互动类型
        comment.setUserId(userId);//用户Id
//        comment.setPublishUserId(0L);
        comment.setCreated(System.currentTimeMillis());
//        comment.setLikeCount(0);
        //保存互动数据
        Integer countLike = commentsApi.saveComments(comment);

        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.opsForHash().put(key,hashKey,"1");

        return countLike;
    }

    /**
     * 删除互动喜欢
     * @param movementId
     * @return
     */
    public Integer disLikeComment(String movementId) {
        Long userId = UserHolder.getUserId();
        Boolean aBoolean = commentsApi.hasComment(movementId, userId, CommentType.LIKE);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.disLikeError());
        }

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(userId);
        Integer countLike = commentsApi.delete(comment);

        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);

        return countLike;
    }

    //喜欢
    public Integer loveComment(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentsApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LOVE);
        //2、如果已经喜欢，抛出异常
        if(hasComment) {
            disloveComment(movementId);
            throw new BusinessException(ErrorResult.loveError());
        }
        //3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentsApi.saveComments(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    //取消喜欢
    public Integer disloveComment(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentsApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LOVE);
        //2、如果未点赞，抛出异常
        if(!hasComment) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        //3、调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentsApi.delete(comment);
        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    public Integer commentsLike(String commentsId) {
        String key = Constants.COMMENTS_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, commentsId, "1");

        return commentsApi.updateCommentsLike(commentsId, 1);
    }

    public Integer commentsDisLike(String commentsId) {
        String key = Constants.COMMENTS_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, commentsId);

        return commentsApi.updateCommentsLike(commentsId, -1);
    }
}
